<template>
  <div class="homePage">
    <van-popup
      v-model:show="showLeft"
      position="left"
      :style="{ width: '70%', height: '100%' }"
    >
      <div
        class="popupItem"
        v-for="hot in hotMoreList"
        :key="hot._id"
        @click="goToProductDetail(hot._id)"
      >
        <img :src="hot.img" alt="" />
        <div class="right">
          <div class="title">
            <span>
              <van-text-ellipsis rows="2" :content="hot.title" />
            </span>
          </div>
          <div class="price">
            <span>￥{{ hot.price }}</span>
            <!-- <span>首单减100</span> -->
          </div>
        </div>
      </div>
    </van-popup>
    <!-- 顶部标题 -->
    <div class="topTitle">豆去盲盒-全网最捞盲盒</div>
    <!-- 搜索框 -->
    <div class="topInput">
      <van-field v-model="value1" placeholder="qicai" class="inputs">
        <template #left-icon>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-rili"></use>
          </svg>
        </template>
        <template #right-icon>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-lingdang"></use>
          </svg>
        </template>
      </van-field>
    </div>
    <!-- 轮播图 -->
    <div class="swipe">
      <van-swipe class="my-swipe" autoplay="2000" indicator-color="white">
        <van-swipe-item>
          <img
            src="http://img.c418-stal.icu:1456/imgs/surprise/%E8%BD%AE%E6%92%AD%E5%9B%BE1.png"
          />
        </van-swipe-item>
        <van-swipe-item>
          <img
            src="http://img.c418-stal.icu:1456/imgs/surprise/%E8%BD%AE%E6%92%AD%E5%9B%BE1.png"
        /></van-swipe-item>
        <van-swipe-item>
          <img
            src="http://img.c418-stal.icu:1456/imgs/surprise/%E8%BD%AE%E6%92%AD%E5%9B%BE1.png"
        /></van-swipe-item>
        <van-swipe-item>
          <img
            src="http://img.c418-stal.icu:1456/imgs/surprise/%E8%BD%AE%E6%92%AD%E5%9B%BE1.png"
        /></van-swipe-item>
      </van-swipe>
    </div>

    <!-- 热销推荐详情 -->
    <div class="hotBox" @click="handleHotBoxClick">
      <!-- 推荐标题 -->
      <div class="hotTitle">
        <div class="title">热销标题</div>
        <div class="more" @click="showPopup">More></div>
      </div>
      <!-- 内容 -->
      <div class="hotBoxItem">
        <div
          class="hotItem"
          v-for="hot in hotList"
          :key="hot._id"
          @click="goToProductDetail(hot._id)"
        >
          <img :src="hot.img" alt="" />
          <div class="hotItem-title">
            <span>
              <van-text-ellipsis rows="2" :content="hot.title" />
            </span>
          </div>
          <div class="hotItem-price">
            <span>￥{{ hot.price }}</span>
            <!-- <span>首单减100</span> -->
          </div>
        </div>
      </div>
    </div>

    <!-- 一番赏详情 -->
    <div class="appreciateBox">
      <!-- 一番赏标题 -->
      <div class="appreciateTitle">
        <div class="title">一番赏</div>
        <div class="more">More ></div>
      </div>
      <!-- 内容 -->
      <div
        class="appreciateItem"
        v-for="appreciate in totalRemainingQuantities"
        :key="appreciate._id"
      >
        <div class="leftImg">
          <img :src="appreciate.img" alt="" />
        </div>
        <div class="rightTitle">
          <div class="title">
            <van-text-ellipsis rows="2" :content="appreciate.title" />
          </div>
          <div class="p-s">
            <span class="price">
              <span>￥</span>
              <span>{{ appreciate.price }}</span>
            </span>
            <span class="surplus">
              剩余
              {{ appreciate.totalRemaining }}/{{ appreciate.inventory }}
            </span>
          </div>
          <div class="plan">
            <van-progress
              :percentage="appreciate.percentage"
              :show-pivot="false"
              color="#12161e"
              stroke-width="8"
            />
          </div>
          <div class="pinzhiList">
            <div
              v-for="item in appreciate.qualities"
              :key="item._id"
              class="pinzhiItem"
            >
              <div class="text">{{ levelToLetter(item.level) }}赏</div>
              <div class="num">X{{ item.quantity }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新品专区详情 -->
    <div class="newBox">
      <!-- 新品专区标题 -->
      <div class="newTitle">
        <div class="title">新品专区</div>
        <div class="more">More ></div>
      </div>
      <!-- 内容 -->
      <div class="newItem">
        <div v-for="item in newList" :key="item._id" class="newFor">
          <div class="img">
            <img :src="item.img" alt="" />
          </div>
          <div class="title">
            <van-text-ellipsis rows="2" :content="item.title" />
          </div>
          <div class="price">
            <span>￥</span>
            <span>
              {{ item.price }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import apiRequest from "../../api";

import router111 from "@/router";
import axios from "axios";
import { showToast,showDialog } from 'vant';
import { md5 } from 'js-md5';
let type = router111.currentRoute.value.query.type;
let code = router111.currentRoute.value.query.code;
// 保存原始的 baseURL
const originalBaseUrl = axios.defaults.baseURL;
const gotoQQ = async () => {
  // 清除 baseURL（或设置为其他值）
  axios.defaults.baseURL = '';
  await axios.get("/api", {
    params: {
      act: "callback",
      appid: "2999", //自己去官网申请
      appkey: "542aa08d939eff83e30c556875ab134f", //自己去官网申请
      type: type,
      code: code
    },
  }).then((res) => {
    sessionStorage.longtermToken = res.data.access_token
    sessionStorage.shorttermToken = res.data.shorttermToken
    sessionStorage._id = JSON.stringify(res.data.social_uid)
    sessionStorage.username = JSON.stringify(res.data.nickname)
    sessionStorage.pic = JSON.stringify(res.data.faceimg)
    axios.defaults.baseURL = originalBaseUrl;
    oncelogin();
  }).catch((err) => {
    console.log(err);
  })
};


//单设备登录
const oncelogin = () => {
    //浏览器指纹
    const createBrowserFingerprint = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        ctx.fillStyle = 'red'
        ctx.fillRect(0, 0, 1, 1)
        return md5(canvas.toDataURL())
    }
    //谷歌abf12f62e03d160f7f24144ef1778396
    //火狐80bea69bfc7cad5832d12e41714cf677
    //Edge abf12f62e03d160f7f24144ef1778396

    const ws = new WebSocket('ws://127.0.0.1:3000') //socket本地IP+端口
    ws.addEventListener('open', () => {
        ws.send(JSON.stringify({
            action: 'login', //动作登录
            id: sessionStorage._id, //用户ID
            fingerprint: createBrowserFingerprint() //浏览器指纹
        }))
    })
    ws.addEventListener('message', (message) => {
        const data = JSON.parse(message.data)
        if (data.action === 'logout') {
            showDialog({
                message: data.msg,
            }).then(() => {
                sessionStorage.clear()
                router111.push('/login')
            });//监听到挤下线操作提示弹框
        }
    })
}

if(type && code){
  gotoQQ();
}

// 弹出层
const showLeft = ref(false);
const showPopup = () => {
  showLeft.value = true;
};

const router = useRouter();

// 热销列表
const hotList = ref([]);
// 更多热销
const hotMoreList = ref([]);
// 一番赏列表
const appreciateList = ref([]);
// 新品列表
const newList = ref([]);

const value1 = ref("");
// 获取热销列表
const getHotList = async () => {
  try {
    const response = await apiRequest.get("/home/getHotList");
    hotList.value = response.data;
    // console.log(hotList);
  } catch (error) {
    console.log(error);
  }
};
// 获取更多热销列表
const getHotMoreList = async () => {
  try {
    const response = await apiRequest.get("/home/getHotMoreList");
    hotMoreList.value = response.data;
  } catch (error) {
    console.log(error);
  }
};
// 获取一番赏列表
const getAppreciateList = async () => {
  try {
    const response = await apiRequest.get("/home/getAppreciateList");
    appreciateList.value = response.data;
    console.log(response.data);
    // console.log(appreciateList);
  } catch (error) {
    console.log(error);
  }
};
// 获取新品列表
const getNewList = async () => {
  try {
    const response = await apiRequest.get("/home/getNewList");
    newList.value = response.data;
    // console.log(response);
  } catch (error) {
    console.log(error);
  }
};

// 计算库存剩余数量
const totalRemainingQuantities = computed(() => {
  return appreciateList.value.map((item) => {
    const totalRemaining = item.qualities.reduce(
      (sum, quality) => sum + quality.quantity,
      0
    );
    const percentage = Math.round((totalRemaining / item.inventory) * 100);
    return {
      ...item,
      totalRemaining,
      percentage,
    };
  });
});
// 品级替换
const levelToLetter = computed(() => {
  return (level) => {
    const letters = ["A", "B", "C", "D"];
    return level >= 0 && level < letters.length ? letters[level] : level;
  };
});
// 热销购买跳转
const goToProductDetail = (productId) => {
  router.push({ name: "hotBuyView", params: { id: productId } });
};
// 更多热销购买跳转
const goToMoreProductDetail = (productId)=>{
    router.push({name:'hotBuyView',params:{id:productId}})
}

onMounted(() => {
  getHotList();
  getAppreciateList();
  getNewList();
  getHotMoreList();
});
</script>

<style lang="scss" scoped>
.my-swipe .van-swipe-item {
  color: #fff;
  font-size: 20px;
  line-height: 150px;
  text-align: center;
  background-color: #39a9ed;
}
.homePage {
  width: 92%;
  height: 100%;
  margin: 0 auto;
}
.topTitle {
  text-align: center;
  font-weight: 600;
  margin: 1em 0;
}
.topInput {
  .inputs :deep(.van-field__control) {
    height: 2em;
    background-color: #f6f7f9;
    border-radius: 50px;
    margin: 0 1em;
    padding: 0 1em;
  }
  .icon {
    width: 2em;
    height: 2em;
  }
}

// 轮播图
.swipe {
  width: 100%;
  .my-swipe {
    width: 100%;
    height: auto; // 移除固定高度

    .van-swipe-item {
      width: 100%;
      height: auto;
      background-color: transparent; // 移除背景色

      img {
        display: block; // 移除图片底部的小空隙
        width: 100%;
        height: auto;
        object-fit: cover;
      }
    }
  }
}

// 热销标题  一番赏标题
.hotBox,
.appreciateBox,
.newBox {
  .hotTitle,
  .appreciateTitle,
  .newTitle {
    margin: 1em 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      position: relative;
      font-size: 20px;
      padding: 0 0 0 0.8em; // 增加左侧padding以为伪元素留出空间
      font-weight: 700;
      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 10px;
        height: 80%; // 可以调整高度
        background-color: #ff6380;
        border-radius: 50px; // 这里设置圆角，可以根据需要调整
      }
    }
  }
  .more {
    background-color: #ececec;
    padding: 5px;
    border-radius: 50px;
    font-size: 14px;
    font-weight: 600;
    font-family: "微软雅黑";
  }
}
// 热销内容
.hotBoxItem {
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1em;
  margin-top: 1em;

  .hotItem {
    width: 100%;

    &:only-child {
      margin-right: auto;
    }
    &:last-child:nth-child(2n + 1) {
      margin-right: auto;
    }

    img {
      width: 100%;
      height: auto;
      border: 2px solid black;
      border-radius: 5%;
      box-sizing: border-box;
    }
    .hotItem-title {
      font-size: 16px;
      font-weight: 700;
    }
    .hotItem-price {
      font-size: 23px;
      padding: 0.5em 0.5em 0 0;
      font-weight: 700;
    }
  }
}
.appreciateBox {
  width: 100%;
  .appreciateItem {
    display: flex;
    width: 100%;
    height: 9em;
    margin: 1em 0;
    img {
      height: 9em;
      border: 2px solid black;
      border-radius: 5%;
      box-sizing: border-box;
    }
  }
  .rightTitle {
    margin: 0 0 0 10px;
    padding: 0;
    width: 100%;
    // height: 8em;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .title {
      font-weight: 700;
    }
    .p-s {
      display: flex;
      flex: 1;
    }
    .price {
      width: 50%;
      margin-top: 0.5em;
      span {
        color: #ff6380;
        font-weight: 700;

        &:last-child {
          font-size: 1.5em;
        }
      }
    }
    .surplus {
      font-size: 14px;
      color: #888888;
      margin-left: auto;
      margin-top: auto;
    }
    .plan {
      margin: 0.5em 0;
    }
    .pinzhiList {
      display: flex;
      justify-content: space-around;
      .pinzhiItem {
        border-radius: 10%;
        background-color: #e1e1e1;
        width: 3em;
        height: 3em;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: center;
        .text {
          font-weight: 700;
          color: #888888;
        }
        .num {
          font-weight: 700;
        }
      }
    }
  }
}
// 新品专区
.newBox {
  width: 100%;
  .newFor {
    margin-right: 1em;
    .title {
      font-weight: 700;
      height: 3em;
    }
    .price {
      font-weight: 700;
      span {
        &:last-child {
          font-size: 1.2em;
        }
      }
    }
  }
  .newItem {
    display: flex;
    overflow-x: auto;
    scrollbar-width: none;

    img {
      height: 8em;
      border: 2px solid black;
      border-radius: 5%;
      box-sizing: border-box;
    }
  }
}
.popupItem {
  display: flex;
  margin: 1em;
  
  img {
    width: 5em;
    border: 2px solid black;
    box-sizing: border-box;
  }
  .right {
    margin-left: 1em;
    .title {
      font-size: 1em;
      font-weight: bold;
    }
    .price{
        font-size: 1.3em;
        font-weight: bold;
    }
  }
}
</style>